package com.ysyc.driver_ee.activity;


import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.formatter.IFillFormatter;
import com.ysyc.driver_ee.R;
import com.ysyc.driver_ee.api.HttpResource;
import com.ysyc.driver_ee.api.NetworkCallback;
import com.ysyc.driver_ee.api.RetrofitClient;
import com.ysyc.driver_ee.base.BaseActivity;
import com.ysyc.driver_ee.impl.TextViewOnClickListener;
import com.ysyc.driver_ee.manager.TakePictureManager;
import com.ysyc.driver_ee.model.OrderForm;
import com.ysyc.driver_ee.tools.DateUtils;
import com.ysyc.driver_ee.tools.PermissionUtils;
import com.ysyc.driver_ee.tools.SpannableStringUtils;
import com.ysyc.driver_ee.widget.SureAndCancelDialog;
import com.ysyc.driver_ee.widget.TitleView;
import com.ysyc.driver_ee.widget.UploadPhotosPop;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;

/**
 * <p>描述：(这里用一句话描述这个类的作用)</p>
 * 作者： Chan<br>
 * 日期： 2018/11/3 15:15<br>
 * 版本： v1.0<br>
 */
public class OrderDetailsActivity extends BaseActivity {
    @BindView(R.id.title_order_details_view)
    TitleView titleOrderDetailsView;
    @BindView(R.id.orderFromSubmit)
    TextView orderFromSubmit;
    @BindView(R.id.startArriveTime)
    TextView startArriveTime;
    @BindView(R.id.startName)
    TextView startName;
    @BindView(R.id.endName)
    TextView endName;
    @BindView(R.id.projectName)
    TextView projectName;
    @BindView(R.id.principalName)
    TextView principalName;
    @BindView(R.id.shipperName)
    TextView shipperName;
    @BindView(R.id.deliveryName)
    TextView deliveryName;
    @BindView(R.id.remake)
    TextView remake;
    @BindView(R.id.navigationLocation)
    TextView navigationLocation;
    @BindView(R.id.orderFromSubmitll)
    LinearLayout orderFromSubmitll;
    private NetworkCallback<OrderForm> orderFormNetworkCallback;
    private String orderNumber;
    private SureAndCancelDialog sureAndCancelDialog;
    private OrderForm orderForms;
    private NetworkCallback<Object> objectNetworkCallback;

    private UploadPhotosPop uploadPhotosPop;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_details;
    }

    @Override
    protected void initView() {

        orderNumber = getIntent().getStringExtra("orderNumber");
        initNetworkCallback();
        OrderFormStatusNetworkCallback();
        initTitle();
    }

    private void OrderFormStatusNetworkCallback() {
        objectNetworkCallback = new NetworkCallback<>(new HttpResource<Object>() {
            @Override
            public void onSuccess(Object o) {
                Integer status = orderForms.status;
                if (1 ==status){
                    orderForms.status = 2;
                }else if (2 ==status){
                    orderForms.status = 3;
                }else if (3 ==status){
                    orderForms.status = 4;
                }
                orderFromStatus(orderForms.status);

            }

            @Override
            public void onFailure(String errorDes) {

            }

            @Override
            public void onLoading(Dialog dialog) {

            }
        });


    }

    private void initTitle() {
        titleOrderDetailsView.setLeftImg(R.drawable.left_return_icon);
        titleOrderDetailsView.setLeftText("订单详情");
        titleOrderDetailsView.setLeftImgClick(v -> finish());

    }

    private void initNetworkCallback() {
        int layoutType = getIntent().getIntExtra("layoutType", 0);
        if (1 == layoutType) {
            navigationLocation.setVisibility(View.GONE);
            orderFromSubmitll.setVisibility(View.GONE);
        }else {
            navigationLocation.setVisibility(View.VISIBLE);
            orderFromSubmitll.setVisibility(View.VISIBLE);
        }

        orderFormNetworkCallback = new NetworkCallback<>(new HttpResource<OrderForm>() {
            @Override
            public void onSuccess(OrderForm orderForm) {
                dismissDilog();
                orderFromStatus(orderForm.status);
                orderForms = orderForm;
                remake.setText(orderForms.remake);
                SpannableStringUtils.setUpTextStyle(startArriveTime, "装货时间:", DateUtils.orderTime(orderForm.startArriveTime), "#FF333333");
                SpannableStringUtils.setUpTextStyle(startName, "装货位置:", orderForm.startName, "#FF41C659");
                SpannableStringUtils.setUpTextStyle(endName, "卸货位置:", orderForm.endName, "#FF41C659");
                SpannableStringUtils.setUpTextStyle(projectName, "订单所属项目:", orderForm.projectName, "#FF333333");
                SpannableStringUtils.setUpTextStyle(principalName, "订单负责人: ", orderForm.principalName, "#FF41C659", new TextViewOnClickListener() {
                    @Override
                    public void textViewOnClick() {
                        String[] permisson = {Manifest.permission.CALL_PHONE};
                        PermissionUtils.requestPermissions(OrderDetailsActivity.this, 1, permisson, mPermissionGrant);
                    }
                });
                SpannableStringUtils.setUpTextStyle(shipperName, "装货负责人: ", orderForm.shipperName, "#FF41C659", new TextViewOnClickListener() {
                    @Override
                    public void textViewOnClick() {
                        String[] permisson = {Manifest.permission.CALL_PHONE};
                        PermissionUtils.requestPermissions(OrderDetailsActivity.this, 2, permisson, mPermissionGrant);
                    }
                });
                SpannableStringUtils.setUpTextStyle(deliveryName, "收货负责人：", orderForm.deliveryName, "#FF41C659", new TextViewOnClickListener() {
                    @Override
                    public void textViewOnClick() {
                        String[] permisson = {Manifest.permission.CALL_PHONE};
                        PermissionUtils.requestPermissions(OrderDetailsActivity.this, 3, permisson, mPermissionGrant);
                    }
                });
            }

            @Override
            public void onFailure(String errorDes) {
                dismissDilog();
            }

            @Override
            public void onLoading(Dialog dialog) {
                showLoadingDialog();

            }
        });
        Observable<OrderForm> orderFormObservable = RetrofitClient.getInstance().getHttpServices().orderformDetails(orderNumber);
        orderFormNetworkCallback.postRequest(orderFormObservable, null);
    }
//0为未接单 1为已接单(即待装货) 2为到达装货地(即装货中) 3为已装货(即正在送货中) 4为已完成
    private void orderFromStatus(Integer status) {
        if (1 ==status){
            orderFromSubmit.setText("确认到达装货地点");
        }else if (2 ==status){
            orderFromSubmit.setText("确认已装货");
        }else if (3 ==status){
            orderFromSubmit.setText("确认已完成");
        }else if (4 ==status){
            orderFromSubmit.setText("订单完成");
        }
    }

    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case 1:
                    showCallPhone(orderForms.principalName, orderForms.principalTel);
                    break;
                case 2:
                    showCallPhone(orderForms.shipperName, orderForms.shipperTel);
                    break;
                case 3:
                    showCallPhone(orderForms.deliveryName, orderForms.deliveryTel);
                    break;
                case 4:
                    Intent intent = new Intent(OrderDetailsActivity.this, OrderNavigationActivity.class);
                    intent.putExtra("OrderForm", orderForms);
                    startActivityForResult(intent, 0X003);
                    break;


                default:
                    break;
            }
        }
    };

    private void showCallPhone(String name, String telPhone) {
        if (sureAndCancelDialog == null) {
            sureAndCancelDialog = new SureAndCancelDialog(OrderDetailsActivity.this);
        }
        sureAndCancelDialog.setTitleText("拨打" + name + "电话").setMessageText(telPhone).setSureText("拨打电话").setOnDialogClickListener(dialog -> {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + telPhone));
            //开启系统拨号器
            startActivity(intent);
        });
        sureAndCancelDialog.show();

    }


    public void orderFromSubmit(View view) {
        Integer status = orderForms.status;
        if (1 ==status){
            Observable<Object> objectObservable = RetrofitClient.getInstance().getHttpServices().onArrival(orderNumber);
            objectNetworkCallback.postRequest(objectObservable,null);
        }else if (2 ==status){
            if (null == uploadPhotosPop) {
                uploadPhotosPop = new UploadPhotosPop(OrderDetailsActivity.this);
            }
            uploadPhotosPop.photographTv.setVisibility(View.GONE);
            uploadPhotosPop.show(orderFromSubmit, new UploadPhotosPop.OnPopListener() {
                @Override
                public void onPhotographItemClick(LinearLayout ll) {

                }

                @Override
                public void onAlbumItemClick(LinearLayout ll) {
                    TakePictureManager takePictureManager = new TakePictureManager(OrderDetailsActivity.this);
                    takePictureManager.needCrop(false);
                    takePictureManager.startTakeWayByCarema("");
                    takePictureManager.setTakePictureCallBackListener(new TakePictureManager.takePictureCallBackListener() {
                        @Override
                        public void successful(boolean isTailor, String outFilePath, Uri filePath) {
                            Bitmap bitmap = BitmapFactory.decodeFile(outFilePath);
                            uploadMultiFile(outFilePath, type);
                            Drawable drawable = new BitmapDrawable(bitmap);
                            ll.setBackground(drawable);
                        }

                        @Override
                        public void failed(int errorCode, List<String> deniedPermissions) {

                        }
                    });
                }
            },orderFromSubmitll);

        }else if (3 ==status){


        }



    }






    public void navigationLocation(View view) {
        String[] permisson = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS};
        PermissionUtils.requestPermissions(this, 4, permisson, mPermissionGrant);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }



}
